package com.izhang3.proxy.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Random;


public class ProxyIpCheckUtils {

    private static Logger logger = LoggerFactory.getLogger(ProxyIpCheckUtils.class);

    private static final String[] ua = {"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)",
            "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)",
            "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)",
            "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)",
            "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)",
            "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; ARM; Trident/6.0)",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8) AppleWebKit/536.25 (KHTML, like Gecko) Version/6.0 Safari/536.25"};


    private static final int HTTP_CONNECT_TIMEOUT = 1000 * 3;

    private static final int HTTP_READ_TIMEOUT = 1000 * 3;


    public static Boolean checkIpProxy(String ip) {
        logger.info("begin 检查代理IP是否正常访问 ip={} ", ip);
        Boolean result = check(ip);
        logger.info("end 检查代理IP是否正常访问 ip={} result={} ", ip, result);
        return result;
    }

    /**
     * 检查代理IP是否能正常访问
     *
     * @param ip
     * @return
     */
    private static Boolean check(String ip) {
        try {
            String[] ss = ip.split(":");
            Proxy proxy = new Proxy(Proxy.Type.HTTP,
                    new InetSocketAddress(ss[0], Integer.parseInt(ss[1])));
            return check(proxy);
        } catch (Exception e) {

        }
        return false;
    }


    /**
     * 检查代理是否正常
     *
     * @param proxy
     * @return
     */
    private static Boolean check(Proxy proxy) {
        URL url;
        HttpURLConnection uc = null;
        try {
            url = new URL("http://www.baidu.com/");
            uc = (HttpURLConnection) url.openConnection(proxy);
            String userAgent = ua[new Random().nextInt(ua.length - 1)];
            uc.setRequestProperty("User-Agent", userAgent);
            uc.setReadTimeout(HTTP_READ_TIMEOUT);
            uc.setConnectTimeout(HTTP_CONNECT_TIMEOUT);
            uc.connect();
            int code = uc.getResponseCode();
            return code == 200;
        } catch (Exception e) {
            return false;
        } finally {
            if (uc != null) {
                uc.disconnect();
            }
        }
    }
}
